package sys

import (
	"errors"
	"faker/project-public/global"
	"faker/project-public/model/sys"
	"faker/project-public/request"
	"faker/project-public/utils"
	"fmt"
	"gorm.io/gorm"
)

type UserService struct {
}

// Login 登录
func (userService *UserService) Login(u sys.SysUser) (userInter *sys.SysUser, err error) {
	if nil == global.FAKER_DB {
		return nil, fmt.Errorf("db not init")
	}
	var user sys.SysUser
	err = global.FAKER_DB.Where("username = ?", u.Username).Preload("Roles").Preload("Role").First(&user).Error
	if err == nil {
		if ok := utils.BcryptCheck(u.PasswordHash, user.PasswordHash); !ok {
			return nil, errors.New("密码错误")
		}
	}
	return &user, err
}

// CreateUser 创建用户
func (userService *UserService) CreateUser(u sys.SysUser) (userInter sys.SysUser, err error) {
	var user sys.SysUser
	if !errors.Is(global.FAKER_DB.Where("username = ?", u.Username).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
		return userInter, errors.New("用户名已注册")
	}
	// 否则 附加uuid 密码hash加密 注册
	u.PasswordHash = utils.BcryptHash(u.PasswordHash)

	err = global.FAKER_DB.Create(&u).Error
	return u, err
}

// GetUserInfo 获取用户信息
func (userService *UserService) GetUserInfo(id int) (user sys.SysUser, err error) {
	var reqUser sys.SysUser
	err = global.FAKER_DB.Preload("Roles").Preload("Role").First(&reqUser, "id = ?", id).Error
	return reqUser, err
}

// GetUserList 获取用户列表
func (userService *UserService) GetUserList(info request.UserList) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.FAKER_DB.Model(&sys.SysUser{})
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}
	if info.Username != "" {
		db = db.Where("Username LIKE ?", "%"+info.Username+"%")
	}
	var userList []sys.SysUser
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Preload("Role").Find(&userList).Error

	//type UserWithRoleName struct {
	//	sys.SysUser
	//	RoleName string
	//}
	//
	//var usersWithRoleName []UserWithRoleName
	//
	//err = db.Table("sys_user").
	//	Select("sys_user.*, sys_role.name as role_name").
	//	Joins("JOIN sys_role ON sys_user.role_id = sys_role.id").
	//	Limit(limit).
	//	Offset(offset).
	//	Scan(&usersWithRoleName).
	//	Error
	//
	//if err != nil {
	//	// 处理错误
	//}
	//
	//// 将用户列表转换为 SysUser 对象，并包含 role_name
	//for _, user := range usersWithRoleName {
	//	user.SysUser.RoleName = user.RoleName
	//	userList = append(userList, user.SysUser)
	//}
	return userList, total, err
}

// UpdateUser 更新用户信息
func (userService *UserService) UpdateUser(u sys.SysUser) (err error) {
	var user sys.SysUser
	err = global.FAKER_DB.Where("id = ?", u.ID).First(&user).Error
	if err != nil {
		return errors.New("无此用户")
	}
	if u.PasswordHash == "" {
		u.PasswordHash = user.PasswordHash
	}
	if u.Sex == 0 {
		u.Sex = user.Sex
	}
	if u.CreateTime == 0 {
		u.CreateTime = user.CreateTime
	}
	u.Img = "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png"
	var setUser sys.SysUser
	err = global.FAKER_DB.Where("username = ?", u.Username).Not("id = ?", u.ID).First(&setUser).Error
	if setUser.ID == u.ID {
		return errors.New("用户名重复")
	}
	var userRole sys.SysUserRole
	userRoleErr := global.FAKER_DB.Where("sys_user_id = ?", u.ID).Delete(&userRole).Error
	if errors.Is(userRoleErr, gorm.ErrRecordNotFound) {
		return errors.New("删除用户关联失败")
	}
	err = global.FAKER_DB.Save(&u).Error
	return err
}

// DeleteUser 删除用户信息
func (userService *UserService) DeleteUser(id int) (err error) {
	var userInfo sys.SysUser
	tx := global.FAKER_DB.Begin()
	err = tx.Where("id = ?", id).First(&userInfo).Error
	if err != nil {
		return errors.New("无此用户")
	}
	err = tx.Where("id = ?", id).Delete(&userInfo).Error
	var userRoleInfo sys.SysUserRole
	err = tx.Where("sys_user_id = ?", id).Delete(&userRoleInfo).Error
	if err != nil {
		tx.Rollback()
		return errors.New("删除失败")
	}
	tx.Commit()
	return err
}

// ChangePassword 修改密码
func (userService *UserService) ChangePassword(u *sys.SysUser, passwordHash string, newPassword string) (userInter *sys.SysUser, err error) {
	var user sys.SysUser
	if err = global.FAKER_DB.Where("id = ?", u.ID).First(&user).Error; err != nil {
		return nil, err
	}
	if ok := utils.BcryptCheck(u.PasswordHash, user.PasswordHash); !ok {
		return nil, errors.New("原密码错误")
	}

	if ok := utils.BcryptCheck(passwordHash, utils.BcryptHash(newPassword)); !ok {
		return nil, errors.New("两次输入的密码不一致")
	}

	user.PasswordHash = utils.BcryptHash(newPassword)
	err = global.FAKER_DB.Save(&user).Error
	return &user, err

}
